package com.whfc.ms.api.fmam.service.impl;

import com.sargeraswang.util.ExcelUtil.ExcelLogs;
import com.sargeraswang.util.ExcelUtil.ExcelUtil;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.generator.KeyGeneratorUtil;
import com.whfc.common.result.ListData;
import com.whfc.common.result.PageData;
import com.whfc.fmam.entity.dto.FmamMatDTO;
import com.whfc.fmam.entity.dto.FmamMatImportDTO;
import com.whfc.fmam.entity.dto.FmamMatImportResultDTO;
import com.whfc.fmam.entity.dto.FmamMatTypeDTO;
import com.whfc.fmam.entity.qo.*;
import com.whfc.fmam.service.FmamMatService;
import com.whfc.ms.api.fmam.service.MatService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author sun_guodong
 * @description 材料字典
 * @date 2019-11-18
 */
@Service
public class MatServiceImpl implements MatService {

    @DubboReference(interfaceClass = FmamMatService.class, version = "1.0.0")
    private FmamMatService fmamMatService;

    @Autowired
    private FileHandler fileHandler;

    @Autowired
    private FilePathConfig filePathConfig;

    /**
     * 材料类别列表
     *
     * @param deptId
     * @param keyword
     * @return
     */
    @Override
    public ListData<FmamMatTypeDTO> matTypeList(Integer deptId, String keyword) {
        List<FmamMatTypeDTO> result = new ArrayList<>();
        List<FmamMatTypeDTO> list = fmamMatService.getMatTypeListByDeptId(deptId, keyword);
        for (FmamMatTypeDTO fmamMatTypeDTO : list) {
            if (fmamMatTypeDTO.getPid() == 0) {
                FmamMatTypeDTO e = new FmamMatTypeDTO();
                e.setId(fmamMatTypeDTO.getId());
                e.setPid(0L);
                e.setCode(fmamMatTypeDTO.getCode());
                e.setFullCode(fmamMatTypeDTO.getFullCode());
                e.setName(fmamMatTypeDTO.getName());
                e.setWeighFlag(fmamMatTypeDTO.getWeighFlag());
                e.setDiffType(fmamMatTypeDTO.getDiffType());
                e.setMinusDiff(fmamMatTypeDTO.getMinusDiff());
                e.setPlusDiff(fmamMatTypeDTO.getPlusDiff());
                List<FmamMatTypeDTO> children = this.getChildren(fmamMatTypeDTO.getId(), list);
                e.setChildren(children.isEmpty() ? null : children);
                result.add(e);
            }
        }
        ListData<FmamMatTypeDTO> listData = new ListData<>(result);
        return listData;
    }

    @Override
    public ListData<FmamMatTypeDTO> matTypeOptionList(Integer deptId) {
        List<FmamMatTypeDTO> list = fmamMatService.getMatTypeListByDeptId(deptId, null);
        ListData<FmamMatTypeDTO> listData = new ListData<>(list);
        return listData;
    }

    /**
     * 新增材料类别
     *
     * @param request
     */
    @Override
    public void matTypeAdd(MatTypeAddQO request) {
        fmamMatService.matTypeAdd(request);
    }

    /**
     * 编辑材料类别
     *
     * @param request
     */
    @Override
    public void matTypeEdit(MatTypeEditQO request) {
        fmamMatService.matTypeEdit(request);
    }

    /**
     * 删除材料类别
     *
     * @param id
     */
    @Override
    public void matTypeDel(Long id) {
        fmamMatService.matTypeDel(id);
    }

    /**
     * 材料列表
     *
     * @param matTypeId
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @Override
    public PageData<FmamMatDTO> matList(Long matTypeId, Integer pageNum, Integer pageSize, String keyword) {
        PageData<FmamMatDTO> pageData = fmamMatService.matList(matTypeId, pageNum, pageSize, keyword);
        return pageData;
    }

    @Override
    public ListData<FmamMatDTO> matList(Integer deptId, Long matTypeId) {
        ListData<FmamMatDTO> listData = fmamMatService.matList(deptId, matTypeId);
        return listData;
    }

    /**
     * 新增材料
     *
     * @param request
     */
    @Override
    public void matAdd(MatAddQO request) {
        fmamMatService.matAdd(request);
    }

    /**
     * 编辑材料
     *
     * @param request
     */
    @Override
    public void matEdit(MatEditQO request) {
        fmamMatService.matEdit(request);
    }

    /**
     * 删除材料
     *
     * @param id
     */
    @Override
    public void matDel(Long id) {
        fmamMatService.matDel(id);
    }


    private List<FmamMatTypeDTO> getChildren(Long id, List<FmamMatTypeDTO> list) {
        List<FmamMatTypeDTO> result1 = new ArrayList<>();
        for (FmamMatTypeDTO fmamMatTypeDTO : list) {
            if (fmamMatTypeDTO.getPid().equals(id)) {
                FmamMatTypeDTO e = new FmamMatTypeDTO();
                e.setId(fmamMatTypeDTO.getId());
                e.setPid(fmamMatTypeDTO.getPid());
                e.setName(fmamMatTypeDTO.getName());
                e.setCode(fmamMatTypeDTO.getCode());
                e.setFullCode(fmamMatTypeDTO.getFullCode());
                e.setWeighFlag(fmamMatTypeDTO.getWeighFlag());
                e.setMinusDiff(fmamMatTypeDTO.getMinusDiff());
                e.setDiffType(fmamMatTypeDTO.getDiffType());
                e.setPlusDiff(fmamMatTypeDTO.getPlusDiff());
                List<FmamMatTypeDTO> children = this.getChildren(fmamMatTypeDTO.getId(), list);
                e.setChildren(children.isEmpty() ? null : children);
                result1.add(e);
            }
        }
        return result1;
    }

    /**
     * 批量导入材料
     *
     * @param file
     */
    @Override
    public FmamMatImportResultDTO importExcel(Integer deptId, MultipartFile file) throws IOException {
        //读取excel中的数据
        Collection<MatImportQO> data = ExcelUtil.importExcel(MatImportQO.class, file.getInputStream(), "yyyy/MM/dd", new ExcelLogs(), null);

        //遍历，获取数据的所有长度
        List<Map<Integer, Integer>> lengthList = new ArrayList<>();
        for (MatImportQO matImportQO : data) {
            String fullCode = matImportQO.getFullCode();
            if (!StringUtils.isEmpty(fullCode)) {
                Integer length = fullCode.length();
                if (lengthList != null && lengthList.size() > 0) { //新目录级别
                    if (length > lengthList.get(lengthList.size() - 1).get(lengthList.size())) {
                        Map<Integer, Integer> map = new HashMap<>();
                        map.put(lengthList.size() + 1, length);
                        lengthList.add(map);
                    }
                } else {
                    Map<Integer, Integer> map = new HashMap<>();
                    map.put(1, length);
                    lengthList.add(map);
                }
            }
            System.out.println(matImportQO.toString());
        }

        //插入物资类型数据及物资数据
        FmamMatImportResultDTO matImportResultDTO = fmamMatService.addExcelMat(deptId, data, lengthList);
        List<FmamMatImportDTO> importResultList = matImportResultDTO.getImportResultList();
        // 将批量导入结果输出到Excel
        String fileName = KeyGeneratorUtil.genStrId() + ".xls";
        File tempFile = File.createTempFile(fileName, "xls");
        tempFile.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(tempFile);
        Map<String, String> headers = new LinkedHashMap<String, String>();
        headers.put("fullCode", "物资编码");
        headers.put("name", "名称");
        headers.put("spec", "规格");
        headers.put("model", "型号");
        headers.put("texture", "材质");
        headers.put("unitName", "计量单位");
        headers.put("diffType", "偏差类型");
        headers.put("plusDiff", "正偏差");
        headers.put("minusDiff", "负偏差");
        headers.put("remark", "备注");
        headers.put("result", "导入结果");
        ExcelUtil.exportExcel(headers, importResultList, fout, "yyyy-MM-dd HH:mm:ss");
        //上传文件到阿里云
        String ossKey = filePathConfig.getFilePath("fmam/temp", fileName);
        String upload = fileHandler.upload(ossKey, new FileInputStream(tempFile));
        matImportResultDTO.setImportResultList(null);
        matImportResultDTO.setImportResultDir(upload);
        return matImportResultDTO;

    }


}



